package com.liu.controller;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liu.domain.JiFen;
import com.liu.domain.student;
import com.liu.model.JsonResult;
import com.liu.repository.JiFenRepository;
import com.liu.repository.StuRepository;
import com.liu.utils.PoiReadExcel;
import com.liu.utils.PoiWriteExcel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.List;

/**
 * Created by liu on 17-9-19.
 */
@RestController
public class StuController {

    private final static Logger logger = LoggerFactory.getLogger(StuController.class);

    @Autowired
    private StuRepository stuRepository;
    @Autowired
    private PoiReadExcel poiReadExcel;
    @Autowired
    private JiFenRepository jiFenRepository;

    @JsonIgnoreProperties(ignoreUnknown = true)

    /*
    查询所有学生列表
     */
    @GetMapping(value = "/stu")
    public String studentList(String target, String searchText){

   /*     System.out.print(target + searchText);
        System.out.println(request.getRequestURL()+"?" + request.getQueryString());*/

//        System.out.print("lalalalal" + searchText);
        //准确查询
        if ("2".equals(target)) {
            List<student> stuCla = stuRepository.findByCla(searchText);
            for (student r: stuCla) {
                int student = r.getRoom_id();
                String r_id = String.valueOf(student);
                String buildId = r_id.substring(0, 2);
                r_id = r_id.substring(2, 5);
                r.setR_id(buildId + "#" + r_id);
            }
            return "{\"code\":0,\"msg\":\"\",\"count\":" + stuCla.size() + ",\"data\":" + stuCla + "}";

        }
        if ("name".equals(target)) {
            String N = "%"+ searchText +"%";
            List<student> stuNam = stuRepository.findMhName(N);
            for (student r: stuNam) {
                int student = r.getRoom_id();
                String r_id = String.valueOf(student);
                String buildId = r_id.substring(0, 2);
                r_id = r_id.substring(2, 5);
                r.setR_id(buildId + "#" + r_id);
            }
            return "{\"code\":0,\"msg\":\"\",\"count\":" + stuNam.size() + ",\"data\":" + stuNam + "}";
        }
        if ("1".equals(target)) {
            String str;
            Integer i = null;
            if(searchText == null ||"".equals(searchText)){
                /*i = Integer.valueOf(searchText);*/
                i = 999;
            }else {
                i = Integer.valueOf(searchText);    //无搜索内容 i为查不到的数据
            }
                List<student> stuNam1 = stuRepository.findByRoom(i);
            for (student r: stuNam1) {
                int student = r.getRoom_id();
                String r_id = String.valueOf(student);
                String buildId = r_id.substring(0, 2);
                r_id = r_id.substring(2, 5);
                r.setR_id(buildId + "#" + r_id);
            }

            return "{\"code\":0,\"msg\":\"\",\"count\":" + stuNam1.size() + ",\"data\":" + stuNam1 + "}";
        }
        if ("stu_id".equals(target)) {
            if (searchText == null ||"".equals(searchText))
            {
                searchText = "不存在";
                return "{\"code\":0,\"msg\":\"\",\"count\":1,\"data\":" +  stuRepository.findById(searchText) + "}";
            }else {
                System.out.print("searchText" + searchText);
                student stuIds = stuRepository.findById(searchText);
                int student = stuIds.getRoom_id();
                String r_id = String.valueOf(student);
                String buildId = r_id.substring(0, 2);
                r_id = r_id.substring(2, 5);
                stuIds.setR_id(buildId + "#" + r_id);
                return "{\"code\":0,\"msg\":\"\",\"count\":1,\"data\":[" + stuIds + "]}";
            }
        }

        List<student> students = stuRepository.findAll();
        for (student r: students) {
            int student = r.getRoom_id();
            String r_id = String.valueOf(student);
            String buildId = r_id.substring(0, 2);
            r_id = r_id.substring(2, 5);
            r.setR_id(buildId + "#" + r_id);
        }

        return "{\"code\":0,\"msg\":\"\",\"count\":" + students.size() + ",\"data\":" + students + "}";

    }
    //session查询
    @GetMapping(value = "/stu/sess")
    @ResponseBody
    public student sessionById(String tea_id ,HttpSession session) {

        student student = (com.liu.domain.student) session.getAttribute("user");
        String id = student.getStu_id();
     /*   System.out.print(tea_id);*/
        // return stuRepository.findById(stu_id);
         student student1 =  stuRepository.findById(id);
        int studen = student1.getRoom_id();
        String r_id = String.valueOf(studen);
        String buildId = r_id.substring(0, 2);
        r_id = r_id.substring(2, 5);
        student1.setR_id(buildId + "#" + r_id);
        return student1;
    }

    /*
    添加一名学生
     */
    @PostMapping(value = "/stu")
    public ModelAndView studentAdd(student stu) {
        stuRepository.save(stu);
        ModelAndView mav = new ModelAndView();
        mav.setViewName("addStu");
        mav.addObject("flag", 1);
        return mav;
    }

    //查询所有班级
    @RequestMapping("/stuAllCla")
    public List<String> stuAllCla(){
        return stuRepository.getCla();
    }

    /*
    更新一个学生的信息
     */
    @PostMapping(value = "/stu/update")
    public boolean stuUpdate(/*teacher tea*/ @RequestBody String date) throws IOException {
        boolean ok = false;
        System.out.println(date);
        ObjectMapper mapper = new ObjectMapper();
        student stu = mapper.readValue(date, student.class);
        System.out.println(stu);
        student s = stuRepository.save(stu);
        if (s != null) {
            ok = true;
        }
        return ok;
    }
    /*
    删除一个学生
     */

    @DeleteMapping(value = "/stu/{stu_id}")
    public void studentDelete(@PathVariable("stu_id") String stu_id){
        System.out.println("dsjkdfjk");
        stuRepository.delete(stu_id);
    }

   /* @RequestMapping("/index")
    public ModelAndView index() {
        ModelAndView mav= new ModelAndView("index");
        return mav;
    }*/



    //通过id查询学生列表
    @GetMapping(value = "/stu/id/{stu_id}")
    public String studentById(@PathVariable("stu_id") String stu_id) {
       // return stuRepository.findById(stu_id);
        return "{\"code\":0,\"msg\":\"\",\"count\":1000,\"data\":" + stuRepository.findById(stu_id) + "}";
    }

    //通过年龄查询



    //通过班级查询
    @GetMapping(value = "/stu/cla/{cla}")
    public List<student> studentByCla(@PathVariable("cla") String cla) {
        return stuRepository.findByCla(cla);
    }

    //通过姓名查询
    @GetMapping(value = "/stu/name/{name}")
    public List<student> studentByName (@PathVariable("name") String name){
    return stuRepository.findByName(name);
        }

 //文件上传 批量增加学生
    @PostMapping("/uploadFile")
    public boolean uploadFile(MultipartFile file) throws IOException {
        boolean ok  = false;
        InputStream inputStream = file.getInputStream();
        ok = poiReadExcel.excelDo(inputStream);
        return ok;
    }

    //学生查看 本班本寝学生
    @RequestMapping("/getRelativeStu")
    public String getClassStu(HttpSession session, String type) {
        student stu = (student) session.getAttribute("user");
        if ("cla".equals(type)) {
            List<student> stus= stuRepository.getClassStu(stu.getCla());
            return "{\"code\":0,\"msg\":\"\",\"count\":" + stus.size() + ",\"data\":" + stuRepository.getClassStu(stu.getCla())+ "}";
        }
        if ("room".equals(type)) {
            return "{\"code\":0,\"msg\":\"\",\"count\":1,\"data\":" + stuRepository.getRoomStu(stu.getRoom_id())+ "}";
        }
        return null;
    }


    @PostMapping("/checkfom")
    public String checkForm(String oldPwd, String newPwd, String reNewPwd, HttpSession session) {
        student student = (com.liu.domain.student) session.getAttribute("user");
        if (!student.getPassword().equals(oldPwd)) {
            return "原密码错误";
        }
        if (!reNewPwd.equals(newPwd)) {
            return "两次输入密码不一致";
        }
        student.setPassword(newPwd);
        stuRepository.save(student);
        return "修改成功";
    }

    @PostMapping("/delStu")
    public boolean delStu(@RequestBody String[] ids) {
        for (String id : ids) {
            stuRepository.delete(id);
        }
        return true;
    }

    // 初始化积分系统，按学期来
    @RequestMapping("/initJF/{year}/{term}")
    public String initJifen(@PathVariable("year") int year,@PathVariable("term") int term){
        List<JiFen> list = jiFenRepository.findAllByYearsAndTerms(year, term);
        if (list.size()>0){
            return "Already";
        }

        return jiFenRepository.initJifenData(year, term)+"";
    }

    //到时间自动删除之前的积分
    @RequestMapping("/jfDel/{year}/{term}")
    public String delJifen(@PathVariable("year") int year,@PathVariable("term") int term) {
        int result = jiFenRepository.dateDel(year,term);
        System.out.println("结果"+result);
        return "ok";
    }

    //积分显示
    @GetMapping(value = "/jifenmain")
    public String healthList(String rid, HttpServletRequest request) {

        if (rid !=null && rid != "") {
            Integer i;
            i = Integer.valueOf(rid);
            List<JiFen> jiFens = jiFenRepository.findByRoom(i);
            for (JiFen r: jiFens) {
                int health = r.getRoomId().getId();
                String r_id = String.valueOf(health);
                String buildId = r_id.substring(0, 2);
                r_id = r_id.substring(2, 5);
                r.setFang(buildId + "#" + r_id);
            }
            return "{\"code\":0,\"msg\":\"\",\"count\":" + jiFens.size() + ",\"data\":" + jiFens + "}";

        }
            List<JiFen> jiFens = jiFenRepository.findAll();
            for (JiFen r : jiFens) {
                int student = r.getRoomId().getId();
                String r_id = String.valueOf(student);
                String buildId = r_id.substring(0, 2);
                r_id = r_id.substring(2, 5);
                r.setFang(buildId + "#" + r_id);
            }
            return "{\"code\":0,\"msg\":\"\",\"count\":" + jiFens.size() + ",\"data\":" + jiFens + "}";

    }


    @GetMapping(value = "/jifenPM")
    public String jfpmList() {
        List<JiFen> jiFens = jiFenRepository.findPM();
        for (JiFen r : jiFens) {
            int student = r.getRoomId().getId();
            String r_id = String.valueOf(student);
            String buildId = r_id.substring(0, 2);
            r_id = r_id.substring(2, 5);
            r.setFang(buildId + "#" + r_id);
        }
        return "{\"code\":0,\"msg\":\"\",\"count\":" + jiFens.size() + ",\"data\":" + jiFens + "}";

    }

        //按寝室查询积分
   /* @GetMapping(value = "/jifenmain")
    public String jifenRoom(String searchHea, HttpServletRequest request) {
        JiFen jiFens = jiFenRepository.findByRoom();
        return "{\"code\":0,\"msg\":\"\",\"count\":" + 1 + ",\"data\":" + jiFens + "}";
    }*/

   //学生主页的积分
    @GetMapping(value = "/grjifen")
    public List<JiFen> grjifen(HttpSession session) {

        student stu = (student) session.getAttribute("user");
        List<JiFen> jiFens = jiFenRepository.findByRoom(stu.getRoom_id());
        return jiFens;
    }







    //导出文件
    @PostMapping("/exportStu")
    public void exportStu(String target, String selectVal, HttpServletResponse res) throws IOException {
        res.setContentType("application/x-download; charset=UTF-8");
        res.setHeader("Content-Disposition", "attachment;filename=export.xls");
        System.out.println(target + " : " + selectVal);
        String json = studentList(target, selectVal);
        ObjectMapper mapper = new ObjectMapper();
        JsonResult result = mapper.readValue(json, JsonResult.class);
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(PoiWriteExcel.writer(result)));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("success");
    }

}



